import { login as loginApi } from '@/api/login' // 登录接口
import router from '@/router/index' // 路由
import { ElMessage } from 'element-plus'

export default {
  namespaced: true,
  // 数据源
  state: () => ({
    token: localStorage.getItem('token') || '',
    menus: localStorage.getItem('menus') || [],
    siderType: true,
    lang: localStorage.getItem('lang') || 'zh',
    size: localStorage.getItem('size') || 'default'
  }),
  mutations: {
    // 设置Token
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    // 左侧菜单伸缩
    // changeSiderType(state, siderType) {
    //   state.siderType = siderType
    // }
    // 左侧菜单伸缩
    changeSiderType(state) {
      state.siderType = !state.siderType
    },
    // 切换语言
    changLang(state, lang) {
      state.lang = lang
    },
    // 切换语言
    changSize(state, size) {
      // console.log(size, 'size')
      state.size = size
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginApi(userInfo)
          .then((res) => {
            if (res.status === 0) {
              commit('setToken', res.token)
              // 调用 user 模块
              commit('user/setUser', res.user, { root: true })
              // 跳转到之前的操作页面或首页
              router.replace(sessionStorage.getItem('path') || '/')
              resolve(true)
            } else {
              ElMessage.error(res.message)
            }
          })
          .catch((err) => {
            console.log(err, 'err')
            reject(err)
          })
      })
    },
    // 退出
    logout({ commit }) {
      commit('setToken', '')
      localStorage.clear()
      router.replace('/login')
    }
    //
    // changeSiderType({ commit }, width) {
    //   commit('changeSiderType', width)
    // }
  }
}
